package com.xh.bussiness.exam.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.exam.bean.dto.ExerciseLearningDto;
import com.xh.bussiness.exam.bean.dto.LearningDto;
import com.xh.bussiness.exam.bean.dto.StudentExerciseDto;
import com.xh.bussiness.exam.bean.request.StudentExerciseRequest;
import com.xh.bussiness.exam.model.Exercise;
import com.xh.bussiness.exam.model.ExerciseStudentQuestion;
import com.xh.bussiness.exam.model.StudentExercise;
import com.xh.bussiness.exam.service.IExerciseService;
import com.xh.bussiness.exam.service.IExerciseStudentQuestionService;
import com.xh.bussiness.exam.service.IStudentExerciseService;
import com.xh.bussiness.permission.model.User;
import com.xh.bussiness.permission.service.IUserService;
import com.xh.bussiness.practice.model.Practice;
import com.xh.bussiness.thirdapi.base.controller.BaseThridTMSController;
import com.xh.bussiness.thirdapi.xuebang.dto.VO.XuebangResultVO;
import com.xh.bussiness.thirdapi.xuebang.dto.request.QueryXuebnagClassLessonRequest;
import com.xh.bussiness.thirdapi.xuebang.service.IXuebangService;
import com.xh.bussiness.tiku.model.Paper;
import com.xh.bussiness.tiku.service.IPaperService;
import com.xh.bussiness.tms.model.StudentAttend;
import com.xh.bussiness.tms.service.IStudentAttendService;
import com.xh.core.bean.AjaxResult;
import com.xh.core.constant.AjaxResultConstant;
import com.xh.core.util.DateUtils;
import com.xh.core.util.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 学生学情管理
 * @author: 赵文博
 * @date: 2021/9/3
 */
@RestController
@RequestMapping("/admin/learing")
public class LearningController {
    @Autowired
    private IStudentExerciseService studentExerciseService;
    @Autowired
    private IXuebangService xuebangService;
    @Autowired
    private IStudentAttendService attendService;
    @Autowired
    private IExerciseService exerciseService;
    @Autowired
    private IPaperService paperService;
    @Autowired
    private IExerciseStudentQuestionService exerciseStudentQuestionService;
    @Autowired
    private IUserService userService;


    /*
     * 学情管理
     * @author 赵文博
     * @date 2021/9/3 17:21
     * @param studentId
     * @return com.xh.core.bean.AjaxResult
     **/
    @PostMapping("/learnManager")
    public AjaxResult getLearnManager(String studentId) {
        List<LearningDto> learningDtos = new ArrayList<>();
        //根据学生id获取已有被评价课次的班级及老师
        List<StudentExercise> studentExercises = studentExerciseService.selectTeacherIdByStudentId(studentId);

            for (StudentExercise studentExercise : studentExercises) {
                LearningDto learningDto = new LearningDto();
                QueryXuebnagClassLessonRequest xuebnagClassLessonRequest = new QueryXuebnagClassLessonRequest();
                xuebnagClassLessonRequest.setTeacherId(Integer.parseInt(studentExercise.getCreatorId()));
                xuebnagClassLessonRequest.setMiniClassId(Integer.parseInt(studentExercise.getClassId()));
                Integer currCount = getTms(xuebnagClassLessonRequest);//该班级总课次

                xuebnagClassLessonRequest.setTeacherId(Integer.parseInt(studentExercise.getCreatorId()));
                xuebnagClassLessonRequest.setMiniClassId(Integer.parseInt(studentExercise.getClassId()));
                xuebnagClassLessonRequest.setCourseDateEnd(DateUtils.format(new Date(),"yyyy-MM-dd"));
                Integer finishCount = getTms(xuebnagClassLessonRequest);//该班级已结束的课次

                //获取当前学生在当前班级已评价过的课次数
                QueryWrapper<StudentExercise> studentExerciseQW = new QueryWrapper<>();
                studentExerciseQW.eq("student_id",studentId);
                studentExerciseQW.eq("class_id",studentExercise.getClassId());
                studentExerciseQW.eq("status",1);
                Integer evaluationCount = studentExerciseService.selectCount(studentExerciseQW);
                //获取当前学生在当前班级出勤的次数
                QueryWrapper<StudentAttend> studentAttendQW = new QueryWrapper<>();
                studentAttendQW.eq("class_id",studentExercise.getClassId());
                studentAttendQW.eq("student_id",studentId);
                studentAttendQW.and(wrapper->wrapper.eq("status",1).or().eq("status",2));
                Integer attendCount = attendService.selectCount(studentAttendQW);
                //学生正确率
                String scoringRate = scoringRate(studentExercise);
                //出勤率
                double attendRate =(attendCount*100/finishCount*100)/100;
                //错题数
                Integer errorCount = errorCount(studentExercise,false);

                learningDto.setScoringRate(scoringRate);
                learningDto.setAttendRate(String.format("%.1f",attendRate));
                learningDto.setCurrCount(currCount);
                learningDto.setEvaluationCount(evaluationCount);
                learningDto.setErrorCount(errorCount);
                learningDto.setClassId(studentExercise.getClassId());
                learningDto.setClassName(studentExercise.getClassName());
                learningDto.setStudentId(studentExercise.getStudentId());
                learningDto.setStudentName(studentExercise.getStudentName());
                learningDtos.add(learningDto);
            }


        //根据班级，老师获取班级的所有课次

        return new AjaxResult(AjaxResultConstant.Result.SUCCESS,"",learningDtos);
    }

    /**
     * 获取学邦数据
     *
     * @return void
     * @author 赵文博
     * @date 2021/9/3 11:52
     **/
    private Integer getTms(QueryXuebnagClassLessonRequest xuebnagClassLessonRequest) {
//        List<ThirdClassLessonDto> resultDatas = new ArrayList<>();
        xuebnagClassLessonRequest.setPageSize(500);
        XuebangResultVO resultVO = xuebangService.queryXuebangClassLesson(xuebnagClassLessonRequest);

        if (resultVO != null && resultVO.getData() != null) {
            List<Object> datas = resultVO.getData().getDatas();
            return datas.size();
//            if (CollectionUtil.isNotEmpty(datas)) {
//                List<ThirdClassLessonDto> collect = datas.stream().map(itme -> {
//                    XuebangClassLesson xuebangClassLesson = BeanUtil.toBean(itme, XuebangClassLesson.class);
//                    ThirdClassLessonDto dto = ThirdClassLessonDto.builder()
//                            .lessonId(xuebangClassLesson.getMiniClassCourseId().toString())
//                            .lessonName(xuebangClassLesson.getMiniClassName())
//                            .courseDate(xuebangClassLesson.getCourseDate())
//                            .courseTime(xuebangClassLesson.getCourseTime())
//                            .miniClassId(xuebangClassLesson.getMiniClassId() == null ? null : xuebangClassLesson.getMiniClassId().toString())
//                            .miniClassName(xuebangClassLesson.getMiniClassName())
//                            .teacherId(xuebangClassLesson.getTeacherId() == null ? null : xuebangClassLesson.getTeacherId().toString())
//                            .teacherName(xuebangClassLesson.getTeacherName())
//                            .build();
//                    return dto;
//                }).collect(Collectors.toList());
//                resultDatas.addAll(collect);
//            }
        }
        return 0;
    }

    /**
     * 得分率 计算当前学生，当前班级所有已评价课次
     * @author 赵文博
     * @date 2021/9/3 17:03
     * @param studentExercise
     * @return java.lang.Double
     **/
    private String scoringRate(StudentExercise studentExercise){
        //查询学生的所有评价信息
        QueryWrapper<StudentExercise> queryWrapper = new QueryWrapper();
        queryWrapper.eq("class_id",studentExercise.getClassId());
        queryWrapper.eq("student_id",studentExercise.getStudentId());
        List<StudentExercise> studentExercises = studentExerciseService.selectList(queryWrapper,StudentExercise.class);
        int j = 0;
        double classRate = 0.0;

        for(StudentExercise studentExercise1 : studentExercises){
            //查询当前课次的试卷
            QueryWrapper<Exercise> exerciseQW = new QueryWrapper<>();
            exerciseQW.eq("curr_id",studentExercise1.getCurrId());
            Exercise exercise = exerciseService.selectFirst(exerciseQW);
            //计算得分率
            int i = 0;
            double rate = 0.0;
            if(studentExercise1.getBeforeScore()!=null){
                Paper paper = paperService.getById(exercise.getBeforePaperId());
                if(paper!=null){
                    Integer totalScore = paper.getTotalScore();
                    if(totalScore!=null && totalScore>0){
                        rate += Double.valueOf(studentExercise1.getBeforeScore()) / totalScore;
                        i++;
                    }
                }
            }
            if(studentExercise1.getBetweenScore()!=null){
                Paper paper = paperService.getById(exercise.getBetweenPaperId());
                if(paper!=null){
                    Integer totalScore = paper.getTotalScore();
                    if(totalScore!=null && totalScore>0){
                        rate += Double.valueOf(studentExercise1.getBetweenScore()) / totalScore;
                        i++;
                    }
                }


            }
            if(studentExercise1.getAfterScore()!=null){
                Paper paper = paperService.getById(exercise.getAfterPaperId());
                if(paper!=null){
                    Integer totalScore = paper.getTotalScore();
                    if(totalScore!=null && totalScore>0){
                        rate += Double.valueOf(studentExercise1.getAfterScore()) / totalScore;
                        i++;
                    }
                }

            }
            if(i>0){
                classRate += rate/i;
                j++;
            }
        }
        if(j>0){
            classRate = classRate/j;
        }
        return String.format("%.1f",classRate*100);
    }

    /**
     * 学情报告 按班级展示每节课的学情管理
     * @author 赵文博
     * @date 2021/9/3 17:23
     * @param request
     * @return void
     **/
    @PostMapping("/classLearnManager")
    public AjaxResult queryClassLearnManager(StudentExerciseRequest request){
        List<StudentExerciseDto> studentExerciseDtos = new ArrayList<>();
        QueryWrapper<StudentExercise> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_id",request.getClassId());
        queryWrapper.eq("student_id",request.getStudentId());
        if(request.getStartDate()!=null &&!"".equals(request.getStartDate()) && request.getEndDate()!=null  &&!"".equals(request.getEndDate())){
            queryWrapper.between("create_time",request.getStartDate()+" 00:00:00",request.getEndDate()+" 23:59:59");
        }
        queryWrapper.orderByDesc("create_time");
        List<StudentExercise> studentExercises = studentExerciseService.selectList(queryWrapper,StudentExercise.class);
        for(StudentExercise studentExercise1 : studentExercises){
            StudentExerciseDto studentExerciseDto = new StudentExerciseDto();
            ObjectUtils.copyNonNullProperties(studentExercise1,studentExerciseDto);
            //未评价
            if(studentExerciseDto.getStatus()==0){
                studentExerciseDto.setScoringRate("0");
                studentExerciseDto.setErrorCount(0);
                studentExerciseDtos.add(studentExerciseDto);
                continue;
            }
            //得分率
            studentExerciseDto.setScoringRate(scoringRate1(studentExercise1));
            //错题数
            studentExerciseDto.setErrorCount(errorCount(studentExercise1,true));
            studentExerciseDtos.add(studentExerciseDto);
        }
        //按月份分组
        Map<String, List<StudentExerciseDto>> stringListMap = studentExerciseDtos.stream().collect(Collectors.groupingBy(item -> DateUtils.format(item.getCreateTime(), "yyyy-MM")));

        return new AjaxResult(AjaxResultConstant.Result.SUCCESS,"",stringListMap);
    }

    /**
     * 计算得分率
     * @author 赵文博
     * @date 2021/9/3 18:08
     * @param studentExercise1
     * @return java.lang.Double
     **/
    private String scoringRate1(StudentExercise studentExercise1){
        //得分率
        QueryWrapper<Exercise> exerciseQW = new QueryWrapper<>();
        exerciseQW.eq("curr_id",studentExercise1.getCurrId());
        Exercise exercise = exerciseService.selectFirst(exerciseQW);
        //计算试卷得分率
        int i = 0;
        double rate = 0.0;
        if(studentExercise1.getBeforeScore()!=null){
            Paper paper = paperService.getById(exercise.getBeforePaperId());
            if(paper!=null){
                Integer totalScore = paper.getTotalScore();//100
                if(totalScore!=null && totalScore>0){
                    rate += Double.valueOf(studentExercise1.getBeforeScore()) / totalScore;
                    i++;
                }
            }


        }
        if(studentExercise1.getBetweenScore()!=null){
            Paper paper = paperService.getById(exercise.getBetweenPaperId());
            if(paper!=null){
                Integer totalScore = paper.getTotalScore();//20
                if(totalScore!=null && totalScore>0){
                    rate += Double.valueOf(studentExercise1.getBetweenScore()) / totalScore;
                    i++;
                }
            }


        }
        if(studentExercise1.getAfterScore()!=null){
            Paper paper = paperService.getById(exercise.getAfterPaperId());
            if(paper!=null){
                Integer totalScore = paper.getTotalScore();//0
                if(totalScore!=null && totalScore>0){
                    rate += Double.valueOf(studentExercise1.getAfterScore()) / totalScore;
                    i++;
                }
            }
        }

        if(i>0){
            rate = rate/i;
        }
        return String.format("%.1f",rate*100);
    }

    /**
     * 查询错题数
     * @author 赵文博
     * @date 2021/9/3 18:21
     * @param studentExercise
     * @param isCurr 为true时只查询当前课次的错题数
     * @return java.lang.Integer
     **/
    private Integer errorCount(StudentExercise studentExercise,boolean isCurr){
        QueryWrapper<ExerciseStudentQuestion> questionQW = new QueryWrapper<>();
        questionQW.eq("class_id",studentExercise.getClassId());
        questionQW.eq("student_id",studentExercise.getStudentId());
        if(isCurr){
            questionQW.eq("curr_id",studentExercise.getCurrId());
        }
        questionQW.eq("correct",0);
        Integer errorCount = exerciseStudentQuestionService.selectCount(questionQW);
        return errorCount;
    }

    @PostMapping("/queryExercise")
    public AjaxResult queryExercise(StudentExerciseRequest request){
        ExerciseLearningDto exerciseLearningDto = new ExerciseLearningDto();
        List<StudentExerciseDto> studentExerciseDtos = studentExerciseService.queryStudentExercises(request);
        Iterator<StudentExerciseDto> iterator = studentExerciseDtos.iterator();
        if(studentExerciseDtos!=null && studentExerciseDtos.size()>0){
            while (iterator.hasNext()){
                StudentExerciseDto dto = iterator.next();
                if(request.getStudentId().equals(dto.getStudentId())){
                    exerciseLearningDto.setStudentExerciseDto(dto);
                    iterator.remove();
                    break;
                }
            }
            getPaperTotalScore(request,exerciseLearningDto);
        }

        exerciseLearningDto.setStudentExerciseDtoList(studentExerciseDtos);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS,"",exerciseLearningDto);
    }

    private void getPaperTotalScore(StudentExerciseRequest request,ExerciseLearningDto exerciseLearningDto){
        QueryWrapper<Exercise> exerciseQW = new QueryWrapper<>();
        exerciseQW.eq("curr_id",request.getCurrId());
        Exercise exercise = exerciseService.selectFirst(exerciseQW);
        if(exercise.getBeforePaperId()!=null){
            exerciseLearningDto.setBeforePaperId(exercise.getBeforePaperId());
            exerciseLearningDto.setBeforeTotalScore(getPaperTotal(exercise.getBeforePaperId()));
        }
        if(exercise.getBetweenPaperId()!=null){
            exerciseLearningDto.setBetweenPaperId(exercise.getBetweenPaperId());
            exerciseLearningDto.setBetweenTotalScore(getPaperTotal(exercise.getBetweenPaperId()));
        }
        if(exercise.getAfterPaperId()!=null){
            exerciseLearningDto.setAfterPaperId(exercise.getAfterPaperId());
            exerciseLearningDto.setAfterTotalScore(getPaperTotal(exercise.getAfterPaperId()));
        }

        exerciseLearningDto.setAfterTotalScore(getPaperTotal(exercise.getAfterPaperId()));
    }
    private Integer getPaperTotal(String paperId){
        if(paperId==null){
            return null;
        }
        QueryWrapper<Paper> paperQW = new QueryWrapper<>();
        paperQW.eq("id",paperId);
        Paper paper = paperService.selectFirst(paperQW);
        if(paper==null){
            return null;
        }
        return paper.getTotalScore();
    }
}